package com.jianyun.jyzs.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.activity.SearchActivity;
import com.jianyun.jyzs.activity.SelectContact2Activity;
import com.jianyun.jyzs.common.IntentRequestCode;
import com.jianyun.jyzs.utils.Const;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.rongcloud.rce.lib.CacheTask;
import cn.rongcloud.rce.lib.GroupTask;
import cn.rongcloud.rce.lib.IMTask;
import cn.rongcloud.rce.lib.RceErrorCode;
import cn.rongcloud.rce.lib.SimpleResultCallback;
import cn.rongcloud.rce.lib.TaskManager;
import cn.rongcloud.rce.lib.UserTask;
import cn.rongcloud.rce.lib.log.RceLog;
import cn.rongcloud.rce.lib.model.GroupInfo;
import cn.rongcloud.rce.lib.model.SearchGroupInfo;
import cn.rongcloud.rce.lib.model.SearchStaffInfo;
import cn.rongcloud.rce.lib.model.StaffInfo;
import cn.rongcloud.rce.lib.utils.PortraitUtils;
import io.rong.imkit.RongIM;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

/**
 * Created by yangshijun on 2018/9/14.
 */

public class DetailSearchFragment  extends SearchFragment {
    @Override
    void doSearch(String content) {

    }

/*    private static final int TIME_DELAY = 300;
    private ViewGroup panelResult;
    private TextView titleView;
    private ListView listView;
    private ViewGroup panelInfo;
    private RelativeLayout searchLoadingPanel;
    private TextView infoText;
    public ResultListAdapter listAdapter;
    private int titleType;
    private String searchText;
    public ArrayList<String> selectedStaffIds;
    private LinearLayout searchLayout;
    public static TextView searchCount;
    public TextView confirm;
    private int from;
    //private Message forwardMessage;
    //private List<Message> forwardMessages;
    private String sendContactMsgUserName;
    private boolean isSingleForward;
    private boolean createNewChat = true;
    private static final String TAG = "StaggeredGridLayoutManager";


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getActivity().getIntent();
        titleType = intent.getIntExtra(SearchActivity.TITLE_TYPE, 0);
        searchText = intent.getStringExtra(SearchActivity.SEARCH_TEXT);
       // forwardMessage = intent.getParcelableExtra(ForwardConst.FORWARD_MESSAGE);
        forwardMessages = intent.getParcelableArrayListExtra(ForwardConst.FORWARD_MESSAGE_LIST);
        isSingleForward = intent.getBooleanExtra(ForwardConst.SINGLE_FORWARD, true);
        selectedStaffIds = getArguments().getStringArrayList(SearchActivity.SELECTED_CONTACT_LIST);
        createNewChat = getArguments().getBoolean(ForwardConst.CREATE_NEW_CHAT);
        from = getArguments().getInt(SearchActivity.FROM);
        StaffInfo staffInfo = CacheTask.getInstance().getMyStaffInfo();
        if (staffInfo != null) {
            sendContactMsgUserName = staffInfo.getName();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.rce_fragment_search_detail, container, false);
        ResultListAdapter.setCountChangedListener(countChangedListener);
        panelResult = (ViewGroup) view.findViewById(  R.id.search_result_panel);
        titleView = (TextView) view.findViewById(  R.id.tv_title);
        listView = (ListView) view.findViewById(  R.id.lv_search_result);
        panelInfo = (ViewGroup) view.findViewById(  R.id.search_info_panel);
        searchLoadingPanel = (RelativeLayout) view.findViewById(  R.id.search_loading_panel);
        infoText = (TextView) view.findViewById(  R.id.search_info_text);
        searchLayout = (LinearLayout) view.findViewById(  R.id.ll_search_bottom);
        searchCount = (TextView) view.findViewById(  R.id.tv_search_count);
        confirm = (TextView) view.findViewById(  R.id.tv_search_confirm);
        listAdapter = new ResultListAdapter(this.getContext());
        Boolean contactSelectable = getArguments().getBoolean(Const.CONTACT_SELECTABLE);
        if (contactSelectable) {
            listAdapter.setOnContactItemClickListener(new OnContactItemClickListener() {
                @Override
                public void onClick(String id, String name, String portrait) {
                    Intent intent = new Intent();
                    intent.putExtra(Const.USER_ID, id);
                    intent.putExtra(Const.USER_NAME, name);
                    intent.putExtra(Const.PORTRAIT, portrait);
                    getActivity().setResult(RESULT_OK, intent);
                    getActivity().finish();
                }
            });
        }
        listView.setAdapter(listAdapter);
        //已选择联系人搜索
        doSearch(getArguments().getString(SearchActivity.SEARCH_TEXT));
        setLayoutShow();
        setButtonClick();
        setSelectedShowText();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        setSelectedShowText();
    }

    private void setLayoutShow() {
        if (from == SearchActivity.FROM_CREATE_GROUP || from == SearchActivity.FROM_FORWARD_CONTACT || from == SearchActivity.FROM_OTHERS) {
            searchLayout.setVisibility(View.VISIBLE);
        } else {
            searchLayout.setVisibility(View.GONE);
        }
    }

    private void setButtonClick() {
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (from) {
                    case SearchActivity.FROM_CREATE_GROUP: // 创建群组
                        final List<String> resultList = new ArrayList<>();
                        for (String key : SelectContact2Activity.getSelectedList().keySet()) {
                            if (selectedStaffIds != null && selectedStaffIds.contains(key)) {
                                continue;
                            }
                            if (!CacheTask.getInstance().getMyStaffInfo().getUserId().equals(key)) {
                                resultList.add(key);
                            }
                        }
                        UserTask.getInstance().getStaffInfoList(resultList, new SimpleResultCallback<List<StaffInfo>>() {
                            @Override
                            public void onSuccessOnUiThread(List<StaffInfo> staffInfos) {
                                createGroup(staffInfos);
                            }
                        });

                        break;
                    case SearchActivity.FROM_FORWARD_CONTACT:
                        if (createNewChat) {  // 转发 创建新聊天
                            final List<String> resultList2 = new ArrayList<>();
                            for (String key : SelectContact2Activity.getSelectedList().keySet()) {
                                if (selectedStaffIds != null && selectedStaffIds.contains(key)) {
                                    continue;
                                }
                                resultList2.add(key);
                            }
                            UserTask.getInstance().getStaffInfoList(resultList2, new SimpleResultCallback<List<StaffInfo>>() {
                                @Override
                                public void onSuccessOnUiThread(List<StaffInfo> staffInfos) {
                                    showCreateGroupForwardDialog(staffInfos);
                                }
                            });
                        } else {
                            showForwardDialog(); // 转发 更多联系人
                        }
                        break;
                    case SearchActivity.FROM_OTHERS: // 群组添加成员
                        List<String> resultList3 = new ArrayList<>();
                        for (String key : SelectContact2Activity.getSelectedList().keySet()) {
                            if (selectedStaffIds != null && selectedStaffIds.contains(key)) {
                                continue;
                            }
                            resultList3.add(key);
                        }
                        UserTask.getInstance().getStaffInfoList(resultList3, new SimpleResultCallback<List<StaffInfo>>() {
                            @Override
                            public void onSuccessOnUiThread(List<StaffInfo> staffInfos) {
                                Intent intent = new Intent();
                                intent.putParcelableArrayListExtra(Const.SELECTED_CONTACTS, (ArrayList<? extends Parcelable>) staffInfos);
                                getActivity().setResult(IntentRequestCode.ADD_GROUP_MEMBER, intent);
                                getActivity().finish();
                            }
                        });
                        break;
                }
            }
        });
        searchCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SelectContact2Activity.getSelectedList().size() > 0) {
                    Intent intent = new Intent(getActivity(), SelectContact2Activity.class);
                    getActivity().startActivityForResult(intent, IntentRequestCode.SEARCH_DETAIL);
                }
            }
        });
    }

    @Override
    void doSearch(final String content) {
        if (TextUtils.isEmpty(content)) {
            panelResult.setVisibility(View.GONE);
            panelInfo.setVisibility(View.GONE);
            searchLoadingPanel.setVisibility(View.GONE);
            return;
        }
        switch (getArguments().getInt(SearchActivity.TYPE)) {
            case SearchActivity.TYPE_CONTACT_SEARCH:
                handleContactSearch(content);
                break;
            case SearchActivity.TYPE_GROUP_SEARCH:
                handleGroupSearch(content, false);
                break;
            case SearchActivity.TYPE_FAV_GROUP_SEARCH:
                handleGroupSearch(content, true);
                break;
            case SearchActivity.TYPE_CONVERSATION_SEARCH:
                handleConversationSearch(content);
                break;
            case SearchActivity.TYPE_MESSAGE_SEARCH:
            case SearchActivity.TYPE_MESSAGE_SEARCH_NO_EDITOR:
                handleMessageSearch(content);
                break;
            case SearchActivity.TYPE_ADD_CONTACT_SEARCH:
            case SearchActivity.TYPE_FORWARD_MORE:
            case SearchActivity.TYPE_CREATE_GROUP:
                handleAddContactSearch(content, from);
                break;
            case SearchActivity.TYPE_GROUP_MEMBER_SEARCH:
                handleGroupMemberSearch(content);
                break;
            case SearchActivity.TYPE_MENTION_GROUP_MEMBER_SEARCH:
                handleMentionGroupMemberSearch(content);
                break;
            case SearchActivity.TYPE_SELECTED_CONTACT_MANAGEMENT:
                handleSelectedContactSearch(content);
                break;
            default:
        }
    }

    private void handleContactSearch(final String content) {
        String departId = getArguments().getString(SearchActivity.DEPART_ID);
        SimpleResultCallback<List<SearchStaffInfo>> callback = new SimpleResultCallback<List<SearchStaffInfo>>() {
            @Override
            public void onSuccessOnUiThread(List<SearchStaffInfo> contactList) {
                ArrayList<ItemModel.PeopleItemModel> modelList = new ArrayList<>();
                for (SearchStaffInfo info : contactList) {
                    ItemModel.PeopleItemModel model = new ItemModel.PeopleItemModel(info);
                    modelList.add(model);
                }
                if (modelList.size() == 0) {
                    showNoResult(content);
                } else {
                    listAdapter.setModelList(modelList, SearchActivity.TYPE_CONTACT_SEARCH, false);
                    showResult(modelList.size());
                }
            }
        };
        if (!TextUtils.isEmpty(departId)) {
            UserTask.getInstance().searchStaffFromDepartment(content, departId, callback);
        } else {
            UserTask.getInstance().searchStaff(content, callback);
        }
    }

    private void handleGroupSearch(final String content, boolean onlySearchFavGroup) {
        GroupTask.getInstance().searchGroupFromDb(content, onlySearchFavGroup, new SimpleResultCallback<List<SearchGroupInfo>>() {
            @Override
            public void onSuccessOnUiThread(List<SearchGroupInfo> searchGroupInfos) {
                ArrayList<ItemModel.GroupItemModel> modelList = new ArrayList<>();
                for (SearchGroupInfo info : searchGroupInfos) {
                    ItemModel.GroupItemModel model = new ItemModel.GroupItemModel(info);
                    modelList.add(model);
                }
                if (modelList.size() == 0) {
                    showNoResult(content);
                } else {
                    listAdapter.setModelList(modelList, SearchActivity.TYPE_GROUP_SEARCH, false);
                    showResult(modelList.size());
                }
            }
        });
    }

    private void handleConversationSearch(final String content) {
        Conversation.ConversationType conversationTypes[] = {Conversation.ConversationType.PRIVATE, Conversation.ConversationType.GROUP};
        String objTypes[] = {"RC:TxtMsg", "RC:ImgTextMsg", "RC:FileMsg"};
        IMTask.IMLibApi.searchConversations(content, conversationTypes, objTypes, new RongIMClient.ResultCallback<List<SearchConversationResult>>() {
            @Override
            public void onSuccess(List<SearchConversationResult> searchConversationResults) {
                ArrayList<ItemModel.ConversationItemModel> modelList = new ArrayList<>();
                final HashMap<String, ItemModel.ConversationItemModel> groupMap = new HashMap<>();
                final HashMap<String, ItemModel.ConversationItemModel> privateMap = new HashMap<>();
                for (SearchConversationResult result : searchConversationResults) {
                    if (result.getConversation().getConversationType() == Conversation.ConversationType.GROUP) {
                        ItemModel.ConversationItemModel model = new ItemModel.ConversationItemModel(result, content, getContext());
                        groupMap.put(result.getConversation().getTargetId(), model);
                        modelList.add(model);
                    } else if (result.getConversation().getConversationType() == Conversation.ConversationType.PRIVATE) {
                        ItemModel.ConversationItemModel model = new ItemModel.ConversationItemModel(result, content, getContext());
                        privateMap.put(result.getConversation().getTargetId(), model);
                        modelList.add(model);
                    }
                }
                if (modelList.size() == 0) {
                    showNoResult(content);
                } else {
                    GroupTask.getInstance().getGroupInfosFromDb(new ArrayList<>(groupMap.keySet()), new SimpleResultCallback<List<GroupInfo>>() {
                        @Override
                        public void onSuccessOnUiThread(List<GroupInfo> groupInfos) {
                            for (GroupInfo info : groupInfos) {
                                ItemModel.ConversationItemModel model = groupMap.get(info.getId());
                                model.name = info.getName();
                                model.portraitUrl = info.getPortraitUrl();
                            }
                            listAdapter.notifyDataSetChanged();
                        }
                    });
                    UserTask.getInstance().getStaffInfoList(new ArrayList<>(privateMap.keySet()), new SimpleResultCallback<List<StaffInfo>>() {
                        @Override
                        public void onSuccessOnUiThread(List<StaffInfo> staffInfos) {
                            for (StaffInfo info : staffInfos) {
                                ItemModel.ConversationItemModel model = privateMap.get(info.getUserId());
                                model.name = info.getName();
                                model.portraitUrl = info.getPortraitUrl();
                            }
                            listAdapter.notifyDataSetChanged();
                        }
                    });
                    listAdapter.setModelList(modelList, SearchActivity.TYPE_CONVERSATION_SEARCH, false);
                    showResult(modelList.size());
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {
                throw new RuntimeException("searchConversations onError, code = " + e);
            }
        });
    }

    private void handleMessageSearch(final String content) {
        final int conversationType = getArguments().getInt(SearchActivity.CONVERSATION_TYPE);
        String conversationId = getArguments().getString(SearchActivity.CONVERSATION_ID);
        final String showName = getArguments().getString(SearchActivity.USER_SHOW_NAME);
        final String portraitUrl = getArguments().getString(SearchActivity.USER_PORTRAIT);
        searchLoadingPanel.setVisibility(View.VISIBLE);
        IMTask.IMLibApi.searchMessages(Conversation.ConversationType.setValue(conversationType), conversationId, content, 50, 0, new RongIMClient.ResultCallback<List<Message>>() {
            @Override
            public void onSuccess(List<Message> messages) {
                final ArrayList<ItemModel.MessageItemModel> modelList = new ArrayList<>();
                for (Message msg : messages) {
                    final ItemModel.MessageItemModel model = new ItemModel.MessageItemModel(msg, getContext());

                    model.name = showName;
                    model.searchShowName = showName;
                    model.portraitUrl = portraitUrl;
                    model.searchStr = content;
                    UserTask.getInstance().getStaffInfo(msg.getSenderUserId(), new SimpleResultCallback<StaffInfo>() {
                        @Override
                        public void onSuccessOnUiThread(StaffInfo staffInfo) {
                            model.portraitUrl = staffInfo.getPortraitUrl();
                            model.searchShowName = staffInfo.getName();
                            modelList.add(model);
                            searchLoadingPanel.setVisibility(View.GONE);
                            if (modelList.size() == 0) {
                                showNoResult(content);
                            } else {
                                listAdapter.setModelList(modelList, SearchActivity.TYPE_MESSAGE_SEARCH, false);
                                showResult(modelList.size());
                            }
                        }

                    });
                }
                if (messages.size() == 0) {
                    searchLoadingPanel.setVisibility(View.GONE);
                    showNoResult(content);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {
                throw new RuntimeException("searchMessages onError, code = " + e);
            }
        });
    }

    private void handleAddContactSearch(final String content, final int from) {
        String departId = getArguments().getString(SearchActivity.DEPART_ID);
        SimpleResultCallback<List<SearchStaffInfo>> callback = new SimpleResultCallback<List<SearchStaffInfo>>() {
            @Override
            public void onSuccessOnUiThread(List<SearchStaffInfo> contactList) {
                ArrayList<ItemModel.PeopleItemModel> modelList = new ArrayList<>();
                for (SearchStaffInfo info : contactList) {
                    ItemModel.PeopleItemModel model = new ItemModel.PeopleItemModel(info);
                    modelList.add(model);
                }
                if (modelList.size() == 0) {
                    showNoResult(content);
                } else {
                    switch (from) {
                        case SearchActivity.FROM_CREATE_GROUP:
                            listAdapter.setModelList(modelList, SearchActivity.TYPE_CREATE_GROUP, false);
                            break;
                        case SearchActivity.FROM_FORWARD_CONTACT:
                            listAdapter.setModelList(modelList, SearchActivity.TYPE_FORWARD_MORE, false);
                            break;
                        case SearchActivity.FROM_OTHERS:
                            listAdapter.setModelList(modelList, SearchActivity.TYPE_ADD_CONTACT_SEARCH, false);
                            break;
                    }
                    showResult(modelList.size());
                }
                setSelectedShowText();
            }
        };
        if (!TextUtils.isEmpty(departId)) {
            UserTask.getInstance().searchStaffFromDepartment(content, departId, callback);
        } else {
            UserTask.getInstance().searchStaff(content, callback);
        }
    }

    private void handleGroupMemberSearch(final String content) {
        String groupId = getArguments().getString(SearchActivity.GROUP_ID);
        UserTask.getInstance().searchStaffFromGroup(content, groupId, new SimpleResultCallback<List<SearchStaffInfo>>() {
            @Override
            public void onSuccessOnUiThread(List<SearchStaffInfo> searchStaffInfos) {
                ArrayList<ItemModel.PeopleItemModel> modelList = new ArrayList<>();
                for (SearchStaffInfo info : searchStaffInfos) {
                    ItemModel.PeopleItemModel model = new ItemModel.PeopleItemModel(info);
                    modelList.add(model);
                }
                if (modelList.size() == 0) {
                    showNoResult(content);
                } else {
                    listAdapter.setModelList(modelList, SearchActivity.TYPE_GROUP_MEMBER_SEARCH, false);
                    showResult(modelList.size());
                }
            }
        });
    }

    private void handleMentionGroupMemberSearch(final String content) {
        titleView.setVisibility(View.GONE);
        String groupId = getArguments().getString(SearchActivity.GROUP_ID);
        UserTask.getInstance().searchStaffFromGroup(content, groupId, new SimpleResultCallback<List<SearchStaffInfo>>() {
            @Override
            public void onSuccessOnUiThread(List<SearchStaffInfo> searchStaffInfos) {
                ArrayList<ItemModel.PeopleItemModel> modelList = new ArrayList<>();
                for (SearchStaffInfo info : searchStaffInfos) {
                    ItemModel.PeopleItemModel model = new ItemModel.PeopleItemModel(info);
                    modelList.add(model);
                }
                if (modelList.size() == 0) {
                    showNoResult(content);
                } else {
                    listAdapter.setModelList(modelList, SearchActivity.TYPE_MENTION_GROUP_MEMBER_SEARCH, false);
                    showResult(modelList.size());
                }
            }
        });
    }

    private void handleSelectedContactSearch(final String content) {
        titleView.setVisibility(View.GONE);
        listAdapter.setRemainingIds(selectedStaffIds);
        List<SearchStaffInfo> searchStaffInfoList = UserTask.getInstance().searchStaffInList(content, selectedStaffIds);
        ArrayList<ItemModel.PeopleItemModel> modelList = new ArrayList<>();
        for (SearchStaffInfo info : searchStaffInfoList) {
            ItemModel.PeopleItemModel model = new ItemModel.PeopleItemModel(info);
            modelList.add(model);
        }
        if (modelList.size() == 0) {
            showNoResult(content);
        } else {
            listAdapter.setModelList(modelList, SearchActivity.TYPE_SELECTED_CONTACT_MANAGEMENT, false);
            showResult(modelList.size());
        }
    }

    private void showNoResult(String content) {
        String searchContent = String.format(getResources().getString(  R.string.rce_search_no_result), content);
        SpannableStringBuilder noResult = new SpannableStringBuilder();
        noResult.append(getResources().getString(  R.string.rce_search_no_result_previous));
        SpannableStringBuilder colorFilterStr = new SpannableStringBuilder(searchContent);
        colorFilterStr.setSpan(new ForegroundColorSpan(getResources().getColor(  R.color.color_primary)), 0, searchContent.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        noResult.append(colorFilterStr);
        noResult.append(getResources().getString(  R.string.rce_search_no_result_end));
        infoText.setText(noResult);
        panelInfo.setVisibility(View.VISIBLE);
        panelResult.setVisibility(View.GONE);
    }

    private void showResult(int count) {
        if (titleType == SearchActivity.TITLE_TYPE_MORE_CONVERSATIONS) {
            titleView.setText(getResources().getString(  R.string.rce_search_chat));
        } else if (titleType == SearchActivity.TITLE_TYPE_CONVERSATION_DETAILS) {
            titleView.setText(getResources().getString(  R.string.rce_search_message_details, count, searchText));
        } else {
            titleView.setText(getResources().getString(  R.string.rce_search_message_details_2, count));
        }
        panelResult.setVisibility(View.VISIBLE);
        panelInfo.setVisibility(View.GONE);
    }

    //判断转发的消息是否是名片消息
    private void startForwardMessage(String id, Conversation.ConversationType type, Message fwdMessage) {
        if ((fwdMessage.getContent() != null) && fwdMessage.getContent() instanceof ContactMessage) {
            ContactMessage contactMessage = ContactMessage.obtain(((ContactMessage) fwdMessage.getContent()).getId(),
                    ((ContactMessage) fwdMessage.getContent()).getName(), ((ContactMessage) fwdMessage.getContent()).getImgUrl(),
                    RongIM.getInstance().getCurrentUserId(), sendContactMsgUserName, null);
            Message message = Message.obtain(id, type, contactMessage);
            IMTask.IMKitApi.sendMessage(message, null, null, (IRongCallback.ISendMediaMessageCallback) null);
        } else {
            Message message = Message.obtain(id, type, fwdMessage.getContent());
            IMTask.IMKitApi.sendMessage(message, null, null, (IRongCallback.ISendMediaMessageCallback) null);
        }
    }

    private void createGroup(List<StaffInfo> staffInfos) {
        if (staffInfos == null || staffInfos.size() == 0) {
            return;
        }
        if (staffInfos.size() == 1) {
            StaffInfo staffInfo = staffInfos.get(0);
            String title;
            if (!TextUtils.isEmpty(staffInfo.getAlias())) {
                title = staffInfo.getAlias();
            } else {
                title = staffInfo.getName();
            }
            IMTask.IMKitApi.startPrivateChat(getActivity(), staffInfo.getUserId(), title);
            getActivity().finish();
        } else {
            Intent intent = new Intent(getActivity(), SetGroupInfoActivity.class);
            intent.putParcelableArrayListExtra(SetGroupInfoActivity.GROUP_MEMBERS, (ArrayList<? extends Parcelable>) staffInfos);
            intent.putExtra(SetGroupInfoActivity.GROUP_FROM, true);
            startActivityForResult(intent, IntentRequestCode.CHAT_GROUP_CREATE);
        }
    }

    private void showForwardDialog() {
        final List<SelectedContactInfo> forwardInfos = new ArrayList<>();
        for (SelectedContactInfo info : SelectContactActivity.getSelectedList().values()) {
            if (info.getId().contains(IMTask.IMKitApi.getCurrentUserId())) {
                continue;
            }
            if (info.getConversationType() == null) {
                SelectedContactInfo selectedContactInfo = new SelectedContactInfo();
                selectedContactInfo.setConversationType(Conversation.ConversationType.PRIVATE);
                selectedContactInfo.setName(info.getName());
                selectedContactInfo.setPortraitUrl(info.getPortraitUrl());
                selectedContactInfo.setId(info.getId());
                forwardInfos.add(selectedContactInfo);
            } else {
                forwardInfos.add(info);
            }
        }
        final ForwardMessageDialog dialog = new ForwardMessageDialog(getActivity());
        dialog.setLayoutRes(  R.layout.rce_dialog_forward_message_selected_contact);
        dialog.setTitle(getString(  R.string.rce_selected_contact_title));
        dialog.setSelectedContactInfoList(forwardInfos);
        dialog.setButtonClickedListener(new ForwardMessageDialog.OnPromptButtonClickedListener() {
            @Override
            public void onPositiveButtonClicked() {
                int count = 0;
                for (final SelectedContactInfo info : forwardInfos) {
                    final Conversation.ConversationType conversationType = info.getConversationType();
                    if (isSingleForward) {
                        TaskManager.getInstance().getBackgroundHandler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startForwardMessage(info.getId(), conversationType, forwardMessage);
                            }
                        }, TIME_DELAY * count);
                        count++;
                    } else {
                        TaskManager.getInstance().getBackgroundHandler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < forwardMessages.size(); i++) {
                                    final int finalI = i;
                                    TaskManager.getInstance().getBackgroundHandler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            startForwardMessage(info.getId(), conversationType, forwardMessages.get(finalI));
                                        }
                                    }, TIME_DELAY * i);
                                }
                            }
                        }, TIME_DELAY * forwardMessages.size() * count);
                        count++;
                    }
                }
                Toast.makeText(getActivity(), getString(  R.string.rce_forward__message_success), Toast.LENGTH_SHORT).show();
                getActivity().setResult(IntentRequestCode.FORWARD_SUCCESS_RETURN);
                getActivity().finish();
            }

            @Override
            public void onNegativeButtonClicked() {

            }
        });
        dialog.show();
    }

    private void showCreateGroupForwardDialog(List<StaffInfo> contactList) {
        final ForwardMessageDialog dialog = new ForwardMessageDialog(getActivity());
        dialog.setLayoutRes(  R.layout.rce_dialog_forward_message_selected_contact);
        dialog.setTitle(getString(  R.string.rce_selected_contact_title));

        float size = getResources().getDimension(  R.dimen.rce_dimen_size_75);
        int count = contactList.size() > 8 ? 9 : contactList.size() + 1;
        List<UserInfo> portraitUrls = new ArrayList<>();
        final List<String> selectedIds = new ArrayList<>();
        selectedIds.add(IMTask.IMLibApi.getCurrentUserId());
        for (StaffInfo staffInfo : contactList) {
            selectedIds.add(staffInfo.getUserId());
        }

        StringBuilder dialogContent = new StringBuilder();
        StaffInfo contactInfo;
        for (int i = 0; i < count && i < contactList.size(); i++) {
            contactInfo = contactList.get(i);
            Uri url = TextUtils.isEmpty(contactInfo.getPortraitUrl()) ? null : Uri.parse(contactInfo.getPortraitUrl());
            UserInfo userInfo = new UserInfo(contactInfo.getUserId(), contactInfo.getName(), url);
            portraitUrls.add(userInfo);
        }
        final String groupName = generateDefaultGroupName(contactList);
        dialogContent.append(groupName);
        dialogContent.append(getString(  R.string.rce_counts, contactList.size()));
        dialog.setName(dialogContent.toString());
        String name = Utils.shortMD5(selectedIds);
        PortraitUtils.getInstance().assembleAvatar(name, (int) size, new PortraitUtils.CreatePortraitCallback() {
            @Override
            public void onCreated(final Bitmap bitmap, File createdFile) {
                RceApp.applicationHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        dialog.setBitmap(bitmap);
                    }
                });
            }

            @Override
            public void onError() {
                RceLog.e(TAG, "createPortrait error");
            }
        }, portraitUrls);

        dialog.setButtonClickedListener(new ForwardMessageDialog.OnPromptButtonClickedListener() {
            @Override
            public void onPositiveButtonClicked() {
                //创建群组，创建成功之后发送消息；
                GroupTask.getInstance().createGroup(groupName, "", selectedIds, new SimpleResultCallback<String>() {
                    @Override
                    public void onSuccessOnUiThread(final String s) {
                        getActivity().setResult(IntentRequestCode.FORWARD_SUCCESS_RETURN);
                        getActivity().finish();
                        if (isSingleForward) {
                            if (forwardMessage != null) {
                                startForwardMessage(s, Conversation.ConversationType.GROUP, forwardMessage);
                            }
                        } else {
                            for (int i = 0; i < forwardMessages.size(); i++) {
                                final int finalI = i;
                                TaskManager.getInstance().getBackgroundHandler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        startForwardMessage(s, Conversation.ConversationType.GROUP, forwardMessages.get(finalI));
                                    }
                                }, TIME_DELAY * i);
                            }
                        }
                        Toast.makeText(getActivity(), getString(  R.string.rce_forward__message_success), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailOnUiThread(RceErrorCode errorCode) {
                        super.onFailOnUiThread(errorCode);
                    }
                });
            }

            @Override
            public void onNegativeButtonClicked() {
                getActivity().setResult(RESULT_CANCELED);
                getActivity().finish();
            }
        });
        dialog.show();
    }

    public void setSelectedShowText() {
        List<SelectedContactInfo> groupList = new ArrayList<>();
        int count = 0;
        if (SelectContactActivity.getSelectedList() != null) {
            for (SelectedContactInfo selectedContactInfo : SelectContactActivity.getSelectedList().values()) {
                if (selectedContactInfo.isCheckable()) {
                    count++;
                    if (!(selectedContactInfo.getConversationType() == null)) {
                        if (selectedContactInfo.getConversationType().equals(Conversation.ConversationType.GROUP)) {
                            groupList.add(selectedContactInfo);
                        }
                    }
                }
            }
            int groupCount = groupList.size();
            int privateCount = count - groupCount;
            if (groupCount == 0) {
                searchCount.setText(getString(  R.string.rce_selected_contacts_count, count));
            } else if (privateCount == 0) {
                searchCount.setText(getString(  R.string.rce_selected_only_group, groupCount));
            } else {
                searchCount.setText(getString(  R.string.rce_selected_contacts_count, privateCount) + getString(  R.string.rce_selected_groups_count, groupCount));
            }
        }

        confirm.setTextColor(count > 0 ?
                getResources().getColor(  R.color.color_primary) :
                getResources().getColor(  R.color.color_gray_text));

        searchCount.setTextColor(count > 0 ?
                getResources().getColor(  R.color.color_primary) :
                getResources().getColor(  R.color.color_gray_text));

        searchCount.setClickable(count > 0 ? true : false);
        confirm.setClickable(count > 0 ? true : false);
    }

    private String generateDefaultGroupName(List<StaffInfo> contact) {
        String groupName = "";
        for (StaffInfo contactInfo : contact) {
            if (!TextUtils.isEmpty(contactInfo.getName())) {
                if (contactInfo.getName().length() > 10) continue;
                if (groupName.length() + contactInfo.getName().length() > 10) break;
                groupName = groupName + contactInfo.getName() + "、";
                if (groupName.length() >= 10) break;
            }
        }
        if (groupName.endsWith("、")) {
            groupName = groupName.substring(0, groupName.length() - 1);
        }
        return groupName;
    }

    ResultListAdapter.CountChangedListener countChangedListener = new ResultListAdapter.CountChangedListener() {
        @Override
        public void onCountChanged() {
            setSelectedShowText();
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        listAdapter.notifyDataSetChanged();
        super.onActivityResult(requestCode, resultCode, data);
    }*/
}

